<script setup>
import bootPopup from '@/components/bootPopup.vue';

import equalProportion from './child/equalProportion.vue';
import libertyExpansion from './child/libertyExpansion.vue';
import Toast from "@vant/weapp/dist/toast/toast";
import newLoading from '@/components/newLoading/index.vue';
import { getCategoryDetail } from "@/api/home";
import { editImgUpload, imgOutPainting, getImageByTaskId } from '@/api/painting'
import { imgUploadVerify } from '@/utils/auth'
import { usePaintingStore } from '@/store';

import { ref, provide } from 'vue';
import { onLoad, onReady, onUnload } from '@dcloudio/uni-app'



const paintingStore = usePaintingStore()


// 画布比例数组
const sizeList = ref([
  {
    id: 1,
    iconfont: "ai-icon-Frame2",
    content: "原图",
  },
  {
    id: 2,
    iconfont: "ai-icon-a-1_1",
    content: "1:1",
  },
  {
    id: 3,
    iconfont: "ai-icon-a-3_4",
    content: "3:4",
  },
  {
    id: 4,
    iconfont: "ai-icon-a-4_3",
    content: "4:3",
  },
  {
    id: 5,
    iconfont: "ai-icon-a-3_4",
    content: "9:16",
  },
  {
    id: 6,
    iconfont: "ai-icon-a-16_9",
    content: "16:9",
  },
]);



// 页面携带参数
const queryItem = ref({})
// 页面参数
const queryParams = ref({
  imageFileUrl: '',
  size: sizeList.value[0].content,
  scale: 1.5,
})
// 查询详情信息
const queryInfo = ref({})
// 提交数据
const queryData = ref({
  model: 'DOUBAO',
  num: 1,
})



// tabs选中
const tabCurrent = ref(0)
// 等比扩图ref
const equalProportionRef = ref(null)
// 自由扩图ref
const libertyExpansionRef = ref(null)

// 消耗算力
const expendNum = ref(0)


const loading = ref(false);
const loadingRef = ref(null);

let timer = null
const taskId = ref('')

// 引导层显示
const bootPopupShow = ref(false)


// 点击顶部navbar标题
function onClickTitle() {
  bootPopupShow.value = true
}



// 点击扩图
async function startFn() {
  clearInterval(timer);
  if (queryParams.value.imageFileUrl === '') {
    Toast.fail('请先选择图片')
    return
  }
  if (queryParams.value.scale === 1 && tabCurrent.value === 0) {
    Toast.fail('请先选择扩图比例')
    return
  }
  if (tabCurrent.value === 0) {
    queryData.value = Object.assign(
      {},
      queryData.value,
      equalProportionRef.value.percent
    )
  } else {
    queryData.value = Object.assign(
      {},
      queryData.value,
      libertyExpansionRef.value.percent
    )
  }
  loading.value = true
  await editImgUploadFn()
  imgOutPaintingFn()
}




// 获取任务状态
async function getImageByTaskIdFn() {
  const res = await getImageByTaskId(taskId.value)
  if (res.data.state === 1) {
    clearInterval(timer);
    await loadingRef.value.completeLoading()
    res.data.title = queryInfo.value.title
    res.data.modelTypeId = queryItem.value.modelTypeId
    uni.navigateTo({
      url: `/draw/expansionPicture/detail/index?data=${JSON.stringify(res.data)}`,
    });
  } else if (![3, 4].includes(res.data.state)) {
    clearInterval(timer);
    const errorMessage = res.data?.remark.split('失败原因：')[1]
    Toast.fail(errorMessage);
    loading.value = false
  }
}


// 发起扩图任务
async function imgOutPaintingFn() {
  try {
    const res = await imgOutPainting(queryData.value)
    paintingStore.setExpansionPictureFn(queryData.value)
    taskId.value = res.data.taskId
    timer = setInterval(() => {
      getImageByTaskIdFn()
    }, 5000);
  } catch (error) {
    loading.value = false
  }
}





// 上传原图
async function editImgUploadFn() {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await editImgUpload({
        type: 8,
        orgImg: queryParams.value.imageFileUrl
      })
      queryData.value.imageUrl = res.orgImgUrl
      resolve()
    } catch (error) {
      const errorMessage = res.data?.remark.split('失败原因：')[1]
      Toast.fail(errorMessage);
      loading.value = false
      reject()
    }
  })
}



// 滑块拖动事件
const sliderDrag = (e) => {
  queryParams.value.scale = e.detail.value
}
// 滑块点击事件
const sliderChange = (e) => {
  queryParams.value.scale = e.detail
}


// 尺寸选择
function sizeItemClick(e) {
  queryParams.value.size = e.content;
}


// tabs切换
function tabsChange(index) {
  tabCurrent.value = index
}



// 上传图片
async function uploadImgFn() {
  const res = await imgUploadVerify()
  queryParams.value.imageFileUrl = res
  queryParams.value.scale = 1.5
}


// 数据转换
function dataConversion() {
  queryInfo.value.categoryParam.forEach(item => {
    if (item.title === 'expendNum') {
      expendNum.value = item.data[0].title
    }
  })
}


// 获取分类详情
async function getCategoryDetailFn() {
  const res = await getCategoryDetail(queryItem.value.id)
  queryInfo.value = res.data
  dataConversion()
}


// 加载关闭事件
function loadingClose() {
  clearInterval(timer);
}

onUnload(() => {
  clearInterval(timer);
  loading.value = false
})

onReady(() => {

})

onLoad((e) => {
  if (e.item) {
    queryItem.value = JSON.parse(e.item)
  }
  getCategoryDetailFn()
})


provide('clickSelectImage', uploadImgFn)
</script>

<template>
  <div class="expansionPicture">
    <NavBar icon="ai-icon-jiaocheng1" @onClickTitle="onClickTitle">{{ queryInfo?.title }}</NavBar>


    <div class="container">
      <div v-if="!queryParams.imageFileUrl" class="uploadImgBtn" @click="uploadImgFn">
        <i class="iconfont ai-icon-xiangcexuanze"></i>
        相册选择
      </div>
      <equalProportion ref="equalProportionRef" v-if="tabCurrent === 0" :imageFileUrl="queryParams.imageFileUrl"
        :scale="queryParams.scale">
      </equalProportion>
      <libertyExpansion ref="libertyExpansionRef" v-else :size="queryParams.size"
        :imageFileUrl="queryParams.imageFileUrl"></libertyExpansion>
    </div>
    <div class="footer">
      <div class="footer_placeholder"></div>
      <div class="footer_content">
        <div class="footer_top">
          <div class="uploadImg" @click="uploadImgFn" v-if="queryParams.imageFileUrl">
            <i class="iconfont ai-icon-shangchuan"></i>
            <div>上传图片</div>
          </div>
          <div class="tabs">
            <div class="tab" :class="{ active: tabCurrent === 0 }" @click="tabsChange(0)">等比扩图</div>
            <div class="tab" :class="{ active: tabCurrent === 1 }" @click="tabsChange(1)">自由扩图</div>
          </div>
        </div>

        <div class="footer_center">
          <div class="slider_box" v-if="tabCurrent === 0">
            <van-slider @drag="sliderDrag" @change="sliderChange" :step="0.01" :value="queryParams.scale" :max="2"
              :min="1" bar-height="16rpx" use-button-slot>
              <template #button>
                <div class="sliderBtn">{{ `${(queryParams.scale * 100).toFixed(0)}%` }}</div>
              </template>
            </van-slider>
          </div>


          <div class="size_list" v-else>
            <div class="size_item" :class="{ active: queryParams.size === item.content }" v-for="item of sizeList"
              @click="sizeItemClick(item)">
              <i :class="`iconfont ${item.iconfont}`"></i>
              <div class="text">{{ item?.content }}</div>
            </div>
          </div>

        </div>

        <div class="create_btn">
          <myDrawButton :expendNum="expendNum" @click="startFn">AI扩图</myDrawButton>
        </div>
      </div>
    </div>
  </div>

  <van-toast id="van-toast"></van-toast>
  <newLoading ref="loadingRef" v-model="loading" :duration="15000" :label="['排队中，预计等待15秒']" @close="loadingClose">
  </newLoading>
  <bootPopup v-model="bootPopupShow" :title="queryInfo?.title" type="8"
    placeholder="上传的图片通过自由角度扩展，AI 会依据图像内容，预测和补充扩展出来的部分。"></bootPopup>
</template>

<style lang="less" scoped>
.expansionPicture {
  height: 100vh;
  display: flex;
  flex-direction: column;

  .container {
    position: relative;
    flex: 1;

    .uploadImgBtn {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 10;
      width: 228rpx;
      height: 84rpx;
      border-radius: 45rpx;
      background-color: transparent;
      border: 3rpx solid var(--a-main-color);
      color: var(--a-one-text-color);
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10rpx;
    }
  }

  .footer {
    .footer_placeholder {
      height: 400rpx;
    }

    .footer_content {
      box-sizing: border-box;
      position: fixed;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 400rpx;
      background: var(--a-main-tabNav-bg-color);
      padding: 30rpx;

      .footer_top {
        position: relative;

        .uploadImg {
          position: absolute;
          left: 0;
          top: -10rpx;
          font-size: 20rpx;
          text-align: center;
          color: var(--a-two-text-color);
        }

        .tabs {
          display: flex;
          align-items: center;
          justify-content: space-evenly;
          color: var(--a-three-text-color);
          font-weight: bold;
          font-size: 32rpx;

          .tab {
            &.active {
              color: var(--a-one-text-color);
            }
          }
        }
      }

      .footer_center {

        .slider_box {
          margin: 60rpx 0 80rpx;
          padding: 0 40rpx;

          .sliderBtn {
            position: relative;
            width: 50rpx;
            height: 50rpx;
            border-radius: 50%;
            background-color: var(--a-main-color);
            border: 5rpx solid #FFF;
            color: var(--a-main-Feature-text-color);
            font-size: 18rpx;
            display: flex;
            align-items: center;
            justify-content: center;
          }
        }

        .size_list {
          display: flex;
          align-items: center;
          gap: 20rpx;
          overflow: scroll;
          margin-top: 30rpx;

          &::-webkit-scrollbar {
            display: none;
          }

          .size_item {
            box-sizing: border-box;
            flex-shrink: 0;
            width: 100rpx;
            height: 120rpx;
            border-radius: 12rpx;
            border: 3rpx solid transparent;
            background: var(--a-main-box-bg-color);
            overflow: hidden;
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            align-items: center;
            font-size: 22rpx;
            color: var(--a-one-text-color);

            .iconfont {
              font-size: 34rpx;
            }

            &.active {
              color: var(--a-main-color);
              border: 3rpx solid var(--a-main-color);
            }
          }
        }
      }

      .create_btn {
        margin-top: 45rpx;
      }
    }
  }
}


/deep/.van-slider__bar {
  background-color: var(--a-main-color) !important;
}
</style>